<template>
  <view class="content">
    <view :style="{ height: `${statusBarHeight}px` }"></view>
    <u-navbar
      :custom-back="customBack"
      back-text="返回"
      title="离线编辑"
    ></u-navbar>
    <!-- <view style="position: absolute; top: 200rpx"> -->
    <web-view
      :src="webSrc"
      :webview-styles="webviewStyles"
      @message="postMessage"
    ></web-view>
    <!-- </view> -->
  </view>
</template>

<script>
import { mapState } from "vuex";
var wv; //计划创建的webview
const info = uni.getSystemInfoSync();
export default {
  data() {
    return {
      statusBarHeight: this.$statusBarHeight,
      webviewStyles: {
        width: "100%",
      },
      webSrc: "/hybrid/html/outlineexcel.html",
      timer: null,
    };
  },
  computed: {
    ...mapState(["localFile"]),
  },
  onReady() {
    // #ifdef APP-PLUS
    var currentWebview = this.$scope.$getAppWebview(); //获取当前页面的webview对象
    let self = this;
    setTimeout(function () {
      wv = currentWebview.children()[0];
      wv.setStyle({
        scalable: true,
        // top: this.$statusBarHeight + 180,
        // height: this.$windowHeight - 180,
        top: info.statusBarHeight + 40,
        height: info.windowHeight - 80,
      });
      self.initWebPage();
    }, 2000); //如果是页面初始化调用时，需要延时一下
    // #endif
  },
  methods: {
    confirm() {
      this.doSave();
    },
    cancel() {
      uni.navigateTo({
        url: "/pages/luckysheet/luckysheet",
      });
    },
    customBack() {
      wv.evalJS(`doExit();`);
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.timer = null;
        this.cancel();
      }, 2000);
    },
    initWebPage() {
      setTimeout(() => {
        this.fetchFileData(this.localFile.fullPath);
      }, 1000);
    },
    doSave() {
      //
      wv.evalJS(`saveFileData();`);
    },

    fetchFileData(path) {
      let root = plus.io.convertLocalFileSystemURL("_downloads/template");
      let rootlen = root.length;
      path = "_downloads/template" + path.slice(rootlen);
      let self = this;
      plus.io.resolveLocalFileSystemURL(
        path,
        (entry) => {
          // 创建或打开， fs.root是根目录操作目录，
          try {
            entry.file((file) => {
              var fileReader = new plus.io.FileReader();
              self.setFileType(file);
              fileReader.readAsDataURL(file, "utf-8");
              // fileReader.readAsText(file, "utf-8");
              fileReader.onloadend = function (res) {
                self.setFileData(res.target.result);
              };
            });
          } catch (error) {
            console.log("报错444", error.message);
          }
        },
        () => {
          console.log("报错3333", e.message);
        }
      );
    },
    // 参数1为文件名称 参数2是文件内容 参数3是回调参数
    saveFile(fileName, fileInfo, callback) {
      // 请求本地文件系统对象
      let path = "data/" + fileName;
      plus.io.requestFileSystem(
        plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
        (entry) => {
          // 文件在手机中的路径

          try {
            entry.root.getFile(
              path,
              { create: true },
              (fileEntry) => {
                fileEntry.createWriter((writer) => {
                  // 写入文件成功完成的回调函数
                  writer.onwrite = (e) => {
                    callback(true);
                  };
                  // 写入数据
                  writer.writeAsBinary(fileInfo);
                });
              },
              (e) => {
                callback(false);
                console.log("报错111", "getFile failed: " + e.message);
              }
            );
          } catch (error) {
            console.log("报错332342", "getFile failed: " + error.message);
          }
        },
        (e) => {
          console.log("报错222", e.message);
          callback(false);
        }
      );
    },
    setFileData(data) {
      this.totalData = data;
      wv.evalJS(`getFileData(${JSON.stringify(data)});`);
    },
    setFileType(data) {
      wv.evalJS(`getFileType(${JSON.stringify(data)});`);
    },
    download(data) {
      let name = new Date().getTime() + "_" + this.localFile.name;
      this.saveFile(
        name,
        data,
        (d) => {
          this.cancel();
        },
        () => {
          this.cancel();
        }
      );
    },
    postMessage(data) {
      let info = data?.detail?.data[0];
      if (info) {
        if (info.type == "data") {
          let xlsxdata = info?.xlsxdata;
          xlsxdata && this.download(xlsxdata);
          // this.cancel();
        } else if (info.type == "save") {
          this.confirm();
        } else if (info.type == "innerexit") {
          clearTimeout(this.timer);
          this.timer = null;
          return;
        } else if (info.type == "cancel") {
          this.cancel();
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  position: relative;
}
.wh-40 {
  height: 40rpx;
}
</style>
